package leetcode.map;

import java.util.Arrays;

public class Lc743 {

    private static final int INF = Integer.MAX_VALUE / 2;


    //Dijkstra单源最短路 朴素实现
    public int networkDelayTime(int[][] times, int n, int k) {

        int[][] graph = new int[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(graph[i], INF);
        }
        boolean[] visited = new boolean[n];
        int[] dist = new int[n];
        Arrays.fill(dist, INF);
        for (int i = 0; i < times.length; i++) {
            graph[times[i][0] - 1][times[i][1] - 1] = times[i][2];
        }
        for (int i = 0; i < n; i++) {
            dist[i] = graph[k - 1][i];
        }
        dist[k - 1] = 0;
        visited[k - 1] = true;
        for (int i = 0; i < n - 1; i++) {
            int min = INF;
            int u = -1;
            for (int j = 0; j < n; j++) {
                if (!visited[j] && dist[j] < min) {
                    min = dist[j];
                    u = j;
                }
            }
            if (u == -1) return -1;
            visited[u] = true;
            for (int j = 0; j < n; j++) {
                if (!visited[j] && dist[u] + graph[u][j] < dist[j]) {
                    dist[j] = dist[u] + graph[u][j];
                }
            }
        }

        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (ans < dist[i])
                ans = dist[i];
        }
        return ans == INF ? -1 : ans;
    }


}
